import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useState } from 'react';
import { Button } from '../ui/button';
import { format } from 'date-fns';

type Props = {
  children?: React.ReactNode;
  setTaskDate: ({ end_date }: { end_date: Date | string }) => void;
  end_date: any;
  clear?(date: string): void;
  side?: 'left' | 'right' | 'top' | 'bottom';
  align?: 'center' | 'end' | 'start';
};

export const DatePicker = ({ children, setTaskDate, end_date, side = 'bottom', align = 'start' }: Props) => {
  const [open, setOpen] = useState<boolean>(false);
  const handleTaskDate = (d: Date) => {
    const d2 = d === undefined ? '' : format(d, 'yyyy-MM-dd');
    setTaskDate({ end_date: d2 });
  };

  const onHandleClear = () => {
    setTaskDate({ end_date: '' });
    setOpen(false);
  }

  return (
    <Popover open={open} onOpenChange={setOpen} >
      {children && <PopoverTrigger onClick={() => setOpen(true)} asChild>{children}</PopoverTrigger>}
      <PopoverContent className='w-auto p-0 z-[99]' align={align} side={side}  >
        <Calendar mode='single' selected={new Date(end_date)} onSelect={handleTaskDate} initialFocus />
        <div className='flex pb-3 justify-evenly' >
          <Button onClick={onHandleClear} variant={'outline'} disabled={end_date === '' ? true : false} >Очистить</Button>
          <Button onClick={() => setOpen(false)} disabled={end_date === '' ? true : false} >Закрыть</Button>
        </div>
      </PopoverContent>
    </Popover>
  );
};
